import { useMemo, useState } from 'react';
import { buildBSTFromArray, getMinimumDifference } from '@ds/tree';
import { Space, Input, Typography, Alert } from 'antd';

export default function BSTMinAbsDiff() {
  const [input, setInput] = useState('4,2,6,1,3');
  const values = useMemo(
    () =>
      input
        .split(/[\,\s]+/)
        .filter(Boolean)
        .map(Number)
        .filter((n) => Number.isFinite(n)),
    [input]
  );
  const root = useMemo(() => buildBSTFromArray(values), [values]);
  const minDiff = useMemo(() => getMinimumDifference(root), [root]);
  const hasEnough = values.length >= 2;

  return (
    <Space direction="vertical" size="middle" style={{ width: '100%' }}>
      <Typography.Title level={2}>LeetCode 530. 二叉搜索树的最小绝对差</Typography.Title>
      <Alert
        message="题目说明"
        description={
          <Typography.Paragraph style={{ marginBottom: 0 }}>
            给定二叉搜索树的根节点，返回树中任意两节点值之间的最小绝对差。
            该页面直接调用算法模块实现（中序遍历 + 相邻差值）。
            <Typography.Link
              href="https://leetcode.cn/problems/minimum-absolute-difference-in-bst/"
              target="_blank"
              style={{ marginLeft: 8 }}
            >
              题目链接
            </Typography.Link>
          </Typography.Paragraph>
        }
        type="info"
        showIcon
      />

      <Space>
        <Input
          allowClear
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="例如: 4,2,6,1,3"
          style={{ width: 360 }}
        />
      </Space>

      <Alert
        message={!hasEnough ? '至少需要两个节点' : `最小绝对差：${minDiff}`}
        type={!hasEnough ? 'warning' : 'success'}
        showIcon
      />

      <Typography.Text type="secondary">
        注：仅调用算法模块并展示结果（未在 UI 中重复实现算法）。
      </Typography.Text>
    </Space>
  );
}
